package com.cl.it.utils;

import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

public class UrlUtils {

    public static String parameter(String url,String key){
        return parameterMap(url).get(key);
    }

    public static Map<String,String> parameterMap(String url){
        Map<String,String> map = new HashMap<String,String>();
        int index = url.indexOf("?");
        if(index != -1) {
            String param = url.substring(index+1);
            if(StringUtils.isNotBlank(param)) {
                String[] params = param.split("&");
                for (String item : params) {
                    String[] kv = item.split("=");
                    if(kv.length > 0) {
                        if(StringUtils.isNotBlank(kv[0])) {
                            String value = "";
                            if(StringUtils.isNotBlank(kv[1])) {
                                int kv1Index = kv[1].indexOf("#");
                                if(kv1Index != -1) {
                                    value = kv[1].substring(0,kv1Index);
                                }else {
                                    value = kv[1];
                                }
                            }
                            map.put(kv[0],value);
                        }
                    }
                }
            }
        }
        return map;
    }

    public static String encode(String url){
        return encode(url, Charset.defaultCharset().name());
    }

    public static String encode(String url,String charset){
        try {
            return url != null ? URLEncoder.encode(url,charset) : null;
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }

    public static String decode(String url){
        return decode(url,Charset.defaultCharset().name());
    }

    public static String decode(String url,String charset){
        try {
            return url != null ? URLDecoder.decode(url, charset) : null;
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }

    public static String nextUrl(String url, String parameter) {
        Map<String, String> map = parameterMap(url);
        String s = map.get(parameter);
        try {
            return URLDecoder.decode(s, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
